<template>
	<a-modal centered v-model:open="visible" bodyStyle="padding:0" :footer="null" class="hhg-modalTable" :wrap-class-name="[hhgWidth ? 'autoHeight-modal' : 'full-modal', hhgHeight ? 'autoWidth-modal' : '']" :width="hhgWidth" :height="hhgHeight" ok-text="确认" cancel-text="取消">
		<div class="tabmain">
			<!-- 主表格 -->
			<div class="baseTable mulTable">
				<a-table :dataSource="hhgDataSource" :columns="hhgColumns" @change="handleTableChange" :showSorterTooltip="false" :rowKey="record=>record.id" :pagination="pagination" v-bind="attrs">
					<template #headerCell="{ column }">
						<div class="columnHead" tabindex="0" v-if="hhgColumns.some(i=> i.search)">
							<div class="inputDiv" :class="[column.search ? '' : 'visibleDiv']" @click.stop @keydown.enter.prevent>
								<a-input v-model:value="column[column.searchKey]" v-bind="attrs" @keydown="handleEnter" @input="handleInput"/>
							</div>
							<div :style="{ textAlign: column.headerAlign }" class="columnTitle">{{ column.title }}</div>
						</div>
					</template>
				</a-table>
			</div>
		</div>
		<!-- 页码 -->
		<div class="pagination" v-if="tableHhgPagination">
			<HhgPagination :total="hhgTotal" ref="paginationRef" @getCurrent="getCurrent" @getPageInfo="getPageInfo"/>
			<a-button @click="filter">Filter</a-button><a-button @click="clearFilter">Clear</a-button>
			<span>显示1到{{hhgPageSize}}，共{{hhgTotal}}条记录</span>
		</div><div style="display: none;">{{hhgColumns}}</div>
		<!-- 拖动 -->
		<template #title>
			<div ref="modalTitleRef" style="width: 100%; cursor: move">选择</div>
		</template>
		<template #modalRender="{ originVNode }">
			<div :style="transformStyle">
				<component :is="originVNode" />
			</div>
		</template>
		<div class="mfoot">
			<a-button :style="{ background: '#3f7fbf', border: '0', color: '#fff' }" type="primary"
				@click="okSubmit">确定</a-button>
			<a-button :style="{ background: '#3f7fbf', border: '0', color: '#fff', margin: '0 12px' }"
				type="primary" @click="clearList">清空</a-button>
			<a-button :style="{ background: '#dddddd', border: '0', color: '#666' }"
				@click="visible = false">关闭</a-button>
		</div>
	</a-modal>
</template>

<script setup>
import { ref, onMounted, defineProps, defineEmits, watch, watchEffect, useAttrs, inject, reactive, defineExpose, computed } from 'vue'
import HhgPagination from './hhg-pagination'
import _ from 'lodash'
//拖动
import { useDraggable } from '@vueuse/core'
//父组件传过来的值
const props = defineProps({
	list: Array,
	columns: Array,
	config: Object,
	loading: Boolean,
	total: Number || String,
	pageSize: Number || String,
	width: Number,
	height: Number,
	type: String,
	displaySearhList: {
            type: Object,
            default: ()=> {}
      },
	hhgPagination: {
            type: Boolean,
            default: ()=> true
      }
})
const pager = inject('pagerTable', ref({
	current: 1,
	pageSize: 10,
	pageSizeOptions: [
		{
			value: 10,
			label: '10',
		},
		{
			value: 20,
			label: '20',
		},
		{
			value: 30,
			label: '30',
		},
	]
}))
//组件属性穿透
const attrs = useAttrs()
//标记搜索
const markInput1 = ref({})
const markInput2 = ref({})

// 创建一个新的数组，避免修改原始的 hhgColumns
const updatedColumns = (list, data) => {
	// 创建一个新的数组，避免修改原始的 list
	const updatedList = list.map(item => {
		// 创建新的 item 对象，保留原有属性
		const newItem = { ...item }
		// 如果该列有 searchKey 并且 data 中存在相应的键
		if (newItem.searchKey && Object.prototype.hasOwnProperty.call(data, newItem.searchKey)) {
			// 将 data 中的值赋给同名属性
			newItem[newItem.searchKey] = data[newItem.searchKey]
		}
		return newItem
	})
	return updatedList
}

//页面切换得到的信息
const parmas = ref({
	current: pager.value.current,
	pageSize: pager.value.pageSize
})
const markCurrent1 = ref(pager.value.current)
const markCurrentBool = ref(false)
const getCurrent = current=> {
	if (!_.isEqual(current, 0)) {
		markCurrent1.value = current
	}
	markCurrentBool.value = false
	parmas.value.current = current
}
const getPageInfo = value=> {
	parmas.value.current = value.current
	parmas.value.pageSize = value.pageSize
	markCurrent1.value = value.current
	markCurrentBool.value = true
	hhgColumns.value = updatedColumns(hhgColumns.value, markInput1.value)
	const newData = _.mapKeys(markInput1.value, function(value, key) {
		return key === 'title_hhg' ? 'title' : key
	})
	emits('getPageInfo', {
		...hhgSorter.value,
		...newData,
		...parmas.value
	})
}
//排序
const hhgSorter = ref({
	sorterKey: '',
	sorterOrder: ''
})
const handleTableChange = (pag, filters, sorter)=> {
	hhgSorter.value.sorterKey = sorter.field
	hhgSorter.value.sorterOrder = sorter.order
	// hhgColumns.value.filter(i=> i.searchKey === sorter.field)[0].sortOrder = sorter.order
	if (_.isEqual(markInput1.value, markInput2.value)) {//点击搜索
		if (!markCurrentBool.value) {
			parmas.value.current = markCurrent1.value
			if (paginationRef.value) {
				paginationRef.value.current = markCurrent1.value
			}
		}
		emits('getPageInfo', {
			...hhgSorter.value,
			..._.mapKeys(markInput2.value, (value, key) => {
				// 如果键是 'hhg_title'，则返回新的键名 'title'
				if (key === 'title_hhg') {
					return 'title'
				}
				// 否则，保持原来的键名不变
				return key
			}),
			...parmas.value
		})
	} else {//没点击搜索
		if (!markCurrentBool.value) {
			parmas.value.current = markCurrent1.value
			if (paginationRef.value) {
				paginationRef.value.current = markCurrent1.value
			}
		}
		hhgColumns.value = updatedColumns(hhgColumns.value, markInput1.value)
		emits('getPageInfo', {
			...hhgSorter.value,
			..._.mapKeys(markInput1.value, (value, key) => {
				// 如果键是 'hhg_title'，则返回新的键名 'title'
				if (key === 'title_hhg') {
					return 'title'
				}
				// 否则，保持原来的键名不变
				return key
			}),
			...parmas.value
		})
	}
}

//子组件通过回车传给父组件方法
const emits = defineEmits(['getPageInfo', 'clearFilter', 'okSubmit', 'clearList'])
const clearList = ()=> {
	emits('clearList')
}
//回显搜索
const displaySearchFn = (parmas, list)=> {
	const data = parmas.map(item => ({
		...item, // 复制现有属性
		searchKey: item.dataIndex // 添加新的 searchKey 属性
	}))
	if(list) {
		const updatedData = data.map(item => {
			// 检查 list 中是否存在对应的 key
			if (Object.prototype.hasOwnProperty.call(list, item.searchKey)) {
				// 如果存在，添加一个新的属性，属性名与 searchKey 相同，并赋值为 list 中的值
				return {
					...item,
					[item.searchKey]: item.searchKey === 'title' ? item[item.searchKey] : list[item.searchKey]
				}
			}
			// 如果不存在，保持原样
			return item
		})
		const value = {}
		updatedData.filter(i=> i.search).forEach(i=> {
			if (i.searchKey === 'title') {
				i.searchKey = 'title_hhg'
				i['title_hhg'] = list['title']
			}
			value[i.searchKey] = i[i.searchKey]
		})
		Object.keys(value).forEach(key => {
			if (value[key] === undefined) {
				value[key] = '' // 或者设置为 null
			}
		})
		markInput1.value = value
		markInput2.value = value
		return updatedData
	} else {
		const value = {}
		data.filter(i=> i.search).forEach(i=> {
			if (i.searchKey === 'title') {
				i.searchKey = 'title_hhg'
			}
			value[i.searchKey] = i[i.searchKey]
		})
		Object.keys(value).forEach(key => {
			if (value[key] === undefined) {
				value[key] = '' // 或者设置为 null
			}
		})
		markInput1.value = value
		markInput2.value = value
		return data
	}
	
}
const visible = ref(false)
const hhgDataSource = ref([])
const hhgTotal = ref(null)
const hhgColumns = ref(displaySearchFn(props.columns, props.displaySearhList))
const hhgPageSize = ref(props.pageSize)
const hhgWidth = ref(props.width)
const hhgHeight = ref(props.height)

const state = reactive({
  selectedRowKeys: [],
  selectdRow: {}
})

//确定按钮提交
const okSubmit = ()=> {
	emits('okSubmit', state.selectdRow)
	visible.value = !visible.value
}

watch(() => props.list, (val) => {
  if (val) {
	hhgDataSource.value = val
  }
}, { immediate: true }, { deep: true })
watch(() => props.pageSize, (val) => {
  if (val) {
	hhgPageSize.value = val
  }
}, { immediate: true }, { deep: true })
watch(() => props.total, (val) => {
  if (val) {
	hhgTotal.value = val
  }
}, { immediate: true }, { deep: true })

const tableHhgPagination = computed(() => {
	if (props.hhgPagination) {
		return props.list.length !== 0 ? true : false
	} else {
		return false
	}
})
// const loading = ref(props.loading)
const paginationRef = ref(null)
//查询方法
const filter = ()=> {
	const value = {}
	hhgColumns.value.filter(i=> i.search).forEach(i=> {
		value[i.searchKey] = i[i.searchKey]
	})
	Object.keys(value).forEach(key => {
		if (value[key] === undefined) {
			value[key] = '' // 或者设置为 null
		}
	})
	if (!markCurrentBool.value) {
		parmas.value.current = markCurrent1.value
		if (paginationRef.value) {
			paginationRef.value.current = markCurrent1.value
		}
	}
	if (_.isEqual(markInput1.value, markInput2.value)) {
		emits('getPageInfo', {
			...hhgSorter.value,
			..._.mapKeys(markInput1.value, (value, key) => {
				// 如果键是 'hhg_title'，则返回新的键名 'title'
				if (key === 'title_hhg') {
					return 'title'
				}
				// 否则，保持原来的键名不变
				return key
			}),
			...parmas.value
		})
	} else {
		markInput1.value = markInput2.value
		paginationRef.value.firstPage(0)
		emits('getPageInfo', {
			...hhgSorter.value,
			..._.mapKeys(markInput2.value, (value, key) => {
				// 如果键是 'hhg_title'，则返回新的键名 'title'
				if (key === 'title_hhg') {
					return 'title'
				}
				// 否则，保持原来的键名不变
				return key
			}),
			current: 1,
			pageSize: parmas.value.pageSize
		})
	}
}
//清空查询
const clearFilter = ()=> {
	if (!_.isEmpty(hhgColumns.value.filter(i=> i.dataIndex === hhgSorter.value.sorterKey))) {
		// 获取所有具有 'aria-sort' 属性元素
		const elements = document.querySelectorAll('.ant-table-column-has-sorters')
		// 遍历这些元素并移除 'aria-sort' 属性
		elements.forEach(function(element) {
			element.removeAttribute('aria-sort')
		})
		hhgSorter.value.sorterKey = ''
		hhgSorter.value.sorterOrder = ''
	}
	const value = {}
	hhgColumns.value.filter(i=> i.search).forEach(i=> {
		value[i.searchKey] = i[i.searchKey]
	})
	hhgColumns.value.forEach(i=> {
		i[i.searchKey] = ''
	})
	Object.keys(value).forEach(key => {
		value[key] = '' // 或者设置为 null
	})
	Object.keys(value).forEach(key => {
		markInput1.value[key] = '' // 或者设置为 null
		markInput2.value[key] = '' // 或者设置为 null
	})
	paginationRef.value.firstPage(0)
	emits('clearFilter', {
		...hhgSorter.value,
		..._.mapKeys(markInput1.value, (value, key) => {
				// 如果键是 'hhg_title'，则返回新的键名 'title'
				if (key === 'title_hhg') {
					return 'title'
				}
				// 否则，保持原来的键名不变
				return key
			}),
		current: 1,
		pageSize: parmas.value.pageSize
	})
}

const handleEnter = (event)=> {
	if (event.key === 'Enter') {
		event.preventDefault() // 阻止默认行为
		event.stopPropagation() // 阻止事件冒泡
		const value = {}
		hhgColumns.value.filter(i=> i.search).forEach(i=> {
			value[i.searchKey] = i[i.searchKey]
		})
		Object.keys(value).forEach(key => {
			if (value[key] === undefined) {
				value[key] = '' // 或者设置为 null
			}
		})
		if (_.isEqual(markInput1.value, markInput2.value)) {
			emits('getPageInfo', {
				...hhgSorter.value,
				..._.mapKeys(value, (value, key) => {
				// 如果键是 'hhg_title'，则返回新的键名 'title'
				if (key === 'title_hhg') {
					return 'title'
				}
				// 否则，保持原来的键名不变
				return key
			}),
				...parmas.value
			})
		} else {
			markInput1.value = value
			markInput2.value = value
			paginationRef?.value?.firstPage(0)
			emits('getPageInfo', {
				...hhgSorter.value,
				..._.mapKeys(value, (value, key) => {
					// 如果键是 'hhg_title'，则返回新的键名 'title'
					if (key === 'title_hhg') {
						return 'title'
					}
					// 否则，保持原来的键名不变
					return key
				}),
				current: 1,
				pageSize: parmas.value.pageSize
			})
		}
	}
}
//监听input输入
const handleInput = ()=> {
	const value = {}
	hhgColumns.value.filter(i=> i.search).forEach(i=> {
		value[i.searchKey] = i[i.searchKey]
	})
	Object.keys(value).forEach(key => {
		if (value[key] === undefined) {
			value[key] = '' // 或者设置为 null
		}
	})
	
	markInput2.value = value
}
//页码相关配置和操作
const pagination = ref(false)
defineExpose({ visible })
//拖动
const modalTitleRef = ref(null)
const { x, y, isDragging } = useDraggable(modalTitleRef)
const startX = ref(0)
const startY = ref(0)
const startedDrag = ref(false)
const transformX = ref(0)
const transformY = ref(0)
const preTransformX = ref(0)
const preTransformY = ref(0)
const dragRect = ref({
	left: 0,
	right: 0,
	top: 0,
	bottom: 0
})
watch([x, y], () => {
	if (!startedDrag.value) {
		startX.value = x.value
		startY.value = y.value
		const bodyRect = document.body.getBoundingClientRect()
		const titleRect = modalTitleRef.value.getBoundingClientRect()
		dragRect.value.right = bodyRect.width - titleRect.width
		dragRect.value.bottom = bodyRect.height - titleRect.height
		preTransformX.value = transformX.value
		preTransformY.value = transformY.value
	}
	startedDrag.value = true
})
watch(isDragging, () => {
	if (!isDragging) {
		startedDrag.value = false
	}
})
watchEffect(() => {
	if (startedDrag.value) {
		transformX.value =
			preTransformX.value +
			Math.min(Math.max(dragRect.value.left, x.value), dragRect.value.right) -
			startX.value;
		transformY.value =
			preTransformY.value +
			Math.min(Math.max(dragRect.value.top, y.value), dragRect.value.bottom) -
			startY.value
	}
})
// mounted
onMounted(() => {})

</script>
<style scoped lang="scss"></style>